<template>
  <!-- <div class="container" v-bind:style="{backgroundImage:'url(' + bg + ')'}"> -->
  <div class="container">
    <!-- <header class="topLogo">
      <img src="../../../static/img/logo.png" alt />
      <span class="title lightSpeedIn">武汉市保障农名工工资支付监管预警平台</span>
    </header> -->
    <loginHeader></loginHeader>
    <div class="mainBox">
      <el-steps :active="active" finish-status="success" align-center>
        <el-step v-if="type === 'QY'" title="填写账号信息"></el-step>
        <el-step v-else title="填写用户信息"></el-step>
        <el-step title="验证身份"></el-step>
        <el-step title="设置新密码"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <div class="firstStep" v-if="active === 0">
        <el-form
          :model="firstForm"
          :rules="ruleFirst"
          ref="firstForm"
          status-icon
          label-width="100px"
          aria-autocomplete="false"
        >
          <el-form-item v-if="type === 'QY'" label="账号" prop="uscc">
            <el-input
              type="text"
              v-model.trim="firstForm.uscc"
              placeholder="输入企业统一社会信用代码或用户名"
              clearable
              @blur="firstForm.uscc = changeValue($event)"
            ></el-input>
          </el-form-item>
          <el-form-item v-else label="账号" prop="userName">
            <el-input
              type="text"
              v-model.trim="firstForm.userName"
              placeholder="输入用户名"
              clearable
              @blur="firstForm.userName = changeValue($event)"
            ></el-input>
          </el-form-item>
          <el-form-item label="图形验证码" prop="vscode">
            <el-input
              class="vscode"
              type="text"
              v-model.trim="firstForm.vscode"
              placeholder="输入验证码"
              clearable
              @blur="firstForm.vscode = changeValue($event)"
            ></el-input>
            <s-identify
              :identifyCode="identifyCode"
              class="imgVscode"
            ></s-identify>
            <el-link @click="refreshCode">看不清换一张</el-link>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="medium"
              class="submitBtn saveBtn saveBtn1"
              @click="submitFisrtForm('firstForm')"
              :loading="canSubmit1"
              >下一步</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="secondStep" v-if="active === 1">
        <div class="messageRemind">
          账号密保手机号
          <span>{{ farmatTel }}</span
          >，请获取验证码完成身份验证
        </div>
        <el-form
          :model="secondForm"
          :rules="ruleSecond"
          ref="secondForm"
          status-icon
          label-width="100px"
          aria-autocomplete="false"
          @submit.native.prevent
        >
          <el-form-item label="短信验证码" prop="phoneCode">
            <el-input
              class="phoneCode"
              type="text"
              v-model.trim="secondForm.phoneCode"
              placeholder="输入短信验证码"
              clearable
              @blur="secondForm.phoneCode = changeValue($event)"
            ></el-input>
            <el-button
              type=""
              class="vscodeBtn btnStyle"
              size="medium"
              v-show="!isCount"
              @click="getVscode()"
              :disabled="canClick"
              >获取验证码</el-button
            >
            <el-button
              type=""
              class="vscodeBtn"
              size="medium"
              v-show="isCount"
              disabled
              >{{ countDownTime }}s后重新获取</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="medium"
              class="submitBtn saveBtn saveBtn1"
              @click="submitSecondForm('secondForm')"
              >下一步</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="thirdStep" v-if="active === 2">
        <!-- <div class="thirdStep"> -->
        <el-form
          :model="thirdForm"
          :rules="ruleThird"
          ref="thirdForm"
          status-icon
          label-width="100px"
          aria-autocomplete="false"
        >
          <!-- <el-form-item label="新密码" prop="password">
            <el-input type="password" v-model.trim="thirdForm.password" show-password placeholder="输入新密码，请妥善保管" clearable @blur="thirdForm.password = changeValue($event)"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="checkPass">
            <el-input type="password" v-model.trim="thirdForm.checkPass" show-password placeholder="请再次输入密码" clearable @blur="thirdForm.checkPass = changeValue($event)"></el-input>
          </el-form-item> -->
          <changePW
            :isFindPW="isFindPW"
            :isDialog="isDialog"
            :isShowUser="isShowUser"
            ref="changePW"
            @toFindPw="toFindPw"
          ></changePW>
          <el-form-item>
            <el-button
              type="primary"
              size="medium"
              class="submitBtn saveBtn saveBtn1"
              @click="toSubmitThirdForm('thirdForm')"
              :loading="canSubmit3"
              >下一步</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="fourStep" v-if="active === 4">
        <img src="../../../static/img/success.png" alt />
        <div class="suceesRemind" style="font-weight: bold">密码修改成功!</div>
        <el-button size="medium" class="submitBtn saveBtn" @click="skipLogin"
          >登录并进入系统</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import common from '../../kits/common'
//引用图形验证码组件
import SIdentify from '@/components/publicCom/identify'

import loginHeader from '@/components/publicCom/loginHeader'
import changePW from '@/components/enterpriseSet/changePassword'
export default {
  name: 'findPassword',
  components: {
    SIdentify,
    loginHeader,
    changePW,
  },
  data() {
    //验证uscc
    var validateUscc = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('统一社会信用代码不能为空'))
      } else {
        var regUscc = /^[0-9A-Z]{2}[0-9]{6}[0-9A-Z]{10}$/
        if (!regUscc.test(value)) {
          callback(new Error('统一社会信用代码格式不正确'))
        }
        callback()
      }
    }
    //验证图形验证码
    var validateImgCode = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('图形验证码不能为空'))
      } else {
        if (value !== this.identifyCode) {
          callback(new Error('图形验证码不正确'))
        }
        callback()
      }
    }
    //验证验证码
    var validatePhoneCode = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('验证码不能为空'))
      } else {
        var url = 'api-u/users/checkvc'
        var data = {
          // tel: this.tel.replace(/\s+/g,''),
          vc: value,
          id: this.userId,
        }
        this.axios({
          method: 'post',
          url: url,
          data: data,
        }).then(
          (res) => {
            if (!res.data.hasError) {
              callback()
            } else {
              callback(new Error(res.data.errorMsg))
            }
          },
          (response) => {
            callback(new Error('验证失败'))
          }
        )
      }
    }
    return {
      bg: require('../../../static/img/login/loginBb.png'), //背景图
      active: 0,
      type: '', //用户类型
      isSend: false, //是否已发送验证码
      canClick: false, //不可以点击发送验证码
      isCount: false, //是否在倒计时
      countDownTime: 60 /*倒计时 计数器*/,
      userId: '', //用户id
      tel: '', //用户手机号
      identifyCodes: '1234567890', //图形验证码
      identifyCode: '',
      canSubmit1: false, //是否可以提交第一步
      canSubmit3: false, //是否可以提交第三步
      firstForm: {
        uscc: '',
        vscode: '',
        userName: '',
      },
      ruleFirst: {
        // uscc: [{ required: true, validator: validateUscc, trigger: "blur" }],
        uscc: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
        userName: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          // {
          //   pattern: /^[a-zA-Z][a-zA-Z0-9_]{4,19}$/,
          //   message: "字母开头，允许字母数字下划线，长度5-20",
          //   trigger: "blur"
          // }
        ],
        vscode: [
          { required: true, validator: validateImgCode, trigger: 'blur' },
        ],
      },
      secondForm: {
        phoneCode: '',
      },
      ruleSecond: {
        phoneCode: [
          { required: true, validator: validatePhoneCode, trigger: 'blur' },
        ],
      },
      isFindPW: true, //是否是忘记密码
      isDialog: true, //是否是首页弹窗
      isShowUser: false,
    }
  },
  computed: {
    farmatTel: function () {
      if (this.tel) {
        return (
          this.tel.substring(0, 4) +
          '****' +
          this.tel.substring(this.tel.length - 3)
        )
      }
    },
  },
  created() {
    this.type = this.$route.query.type ? this.$route.query.type : 'QY'
  },
  mounted() {
    this.identifyCode = ''
    this.makeCode(this.identifyCodes, 4)
  },
  methods: {
    //制作图形验证码
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode +=
          this.identifyCodes[this.randomNum(0, this.identifyCodes.length)]
      }
    },
    //发送验证码倒计时
    countDown() {
      let vm = this
      //开启倒计时
      vm.isCount = true
      var auth_timetimer = setInterval(() => {
        vm.countDownTime--
        if (vm.countDownTime <= 0) {
          vm.isCount = false
          clearInterval(auth_timetimer)
          vm.countDownTime = 60
        }
      }, 1000)
    },
    //发送短信验证码
    getVscode() {
      this.canClick = true
      //验证码倒计时
      let vm = this
      vm.axios({
        method: 'post',
        url: 'api-u/users/sendvc',
        data: {
          // tel: vm.tel,
          id: vm.userId,
        },
      })
        .then(
          (res) => {
            vm.canClick = false
            //已发送验证码
            if (!res.data.hasError) {
              vm.isSend = true
              //验证码倒计时
              this.countDown()
            } else {
              vm.isSend = false
              this.$message({
                showClose: true,
                duration: 3000,
                message: '发送验证码失败',
                type: 'error',
              })
            }
          },
          (res) => {
            vm.isSend = false
            this.$message({
              showClose: true,
              duration: 3000,
              message: '发送验证码失败',
              type: 'error',
            })
            vm.canClick = false
          }
        )
        .catch((error) => {
          vm.canClick = false
        })
    },
    //提交表单第一步
    submitFisrtForm(formName) {
      let vm = this
      vm.canSubmit1 = true
      var url = 'api-c/companyaudit/base/usercompanydetail'
      if (vm.type == 'QY') {
        var data = {
          uscc: vm.firstForm.uscc,
          type: 'COMPANY',
        }
      } else {
        var data = {
          username: vm.firstForm.userName,
          type: 'MONITOR',
        }
      }
      vm.$refs[formName].validate((valid) => {
        if (valid) {
          vm.axios({
            method: 'post',
            url: url,
            data: data,
          })
            .then(
              (res) => {
                vm.canSubmit1 = false
                if (!res.data.hasError) {
                  vm.userId = res.data.result.id
                  vm.tel = res.data.result.tel
                  vm.active++
                } else {
                  this.$message({
                    showClose: true,
                    duration: 3000,
                    message: res.data.errorMsg,
                    type: 'error',
                  })
                  return false
                }
              },
              (res) => {
                this.$message({
                  showClose: true,
                  duration: 3000,
                  message: '提交失败',
                  type: 'error',
                })
                vm.canSubmit1 = false
              }
            )
            .catch((error) => {})
        } else {
          vm.canSubmit1 = false
          return false
        }
      })
    },
    //提交表单第二步()
    submitSecondForm(formName) {
      let vm = this
      vm.$refs[formName].validate((valid) => {
        if (valid) {
          vm.active++
        } else {
          return false
        }
      })
    },
    //提交表单第三步
    toSubmitThirdForm(formName) {
      this.$refs.changePW.submitPassForm()
    },
    toFindPw(password) {
      this.submitThirdForm('thirdForm', password)
    },
    submitThirdForm(formName, password) {
      let vm = this
      vm.canSubmit3 = true
      var url = 'api-u/users/edituser'
      var data = {
        password: password,
        id: vm.userId,
        tel: vm.tel,
        vc: vm.secondForm.phoneCode,
      }
      //vm.active = 4;
      vm.axios({
        method: 'post',
        url: url,
        data: data,
      })
        .then(
          (res) => {
            vm.canSubmit3 = false
            if (!res.data.hasError) {
              vm.active = 4
            } else {
              this.$message({
                showClose: true,
                duration: 3000,
                message: res.data.errorMsg,
                type: 'error',
              })
              return false
            }
          },
          (res) => {
            this.$message({
              showClose: true,
              duration: 3000,
              message: '提交失败',
              type: 'error',
            })
            vm.canSubmit3 = false
          }
        )
        .catch((error) => {})
    },
    //跳转登录
    skipLogin() {
      this.$router.replace({
        path: '#/login/loginFirst',
        name: 'loginFirst',
      })
    },
  },
}
</script>

<style lang="less" scoped>
.container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-size: 100% 100%;
  // text-align: center;
  /* 登录、注册、忘记密码标题的样式 */
  .topLogo {
    text-align: center;
    height: 80px;
    line-height: 80px;
    margin: 3% 0px;
  }
  .topLogo img {
    vertical-align: middle;
    width: 70px;
    height: 79px;
    margin-top: -15px;
  }
  .topLogo .title {
    display: inline-block;
    margin-left: 30px;
    font-size: 36px;
    font-weight: bold;
    color: #fff;
  }
  @media screen and (min-width: 1400px) and (max-width: 1600px) {
    .topLogo {
      margin: 2% 0px;
    }
    .topLogo .title {
      font-size: 30px;
    }
  }
  @media screen and (min-width: 1280px) and (max-width: 1366px) {
    .topLogo {
      margin: 2% 0px;
    }
    .topLogo .title {
      font-size: 30px;
    }
  }
  @media screen and (min-width: 1176px) and (max-width: 1280px) {
    .topLogo {
      margin: 2% 0px;
    }
    .topLogo .title {
      font-size: 28px;
    }
  }
  @media screen and (min-width: 1152px) and (max-width: 1176px) {
    .topLogo {
      margin: 2% 0px;
    }
    .topLogo .title {
      font-size: 26px;
    }
  }
  @media screen and (min-width: 1024px) and (max-width: 1152px) {
    .topLogo {
      margin: 3% 0px;
    }
    .topLogo .title {
      font-size: 26px;
    }
  }
  .mainBox {
    width: 980px;
    background-color: #fff;
    margin: 0 auto;
    border-radius: 10px;
    padding: 50px 70px;
    .suceesRemind {
      font-size: 28px;
      color: #009588;
      margin: 30px 0px 0px;
    }
    /* 步骤条 */
    /deep/ .el-step__head.is-process {
      color: #fff;
      .el-step__icon.is-text {
        border: 2px solid #009588;
        background: #009588;
      }
    }
    .el-steps {
      margin-bottom: 60px;
      /deep/ .el-step__head.is-success,
      /deep/ .el-step__title.is-success {
        color: #009588;
      }

      /deep/ .el-step__head.is-success .el-step__icon.is-text {
        border-color: #009588;
      }

      /deep/ .el-step__line {
        border-color: #009588;
      }
    }

    @media screen and (min-width: 1360px) and (max-width: 1366px) {
      .el-steps {
        margin-bottom: 35px;
      }
    }
    .messageRemind {
      text-align: center;
      margin-bottom: 25px;
      color: #666;
      font-size: 14px;
    }
    .el-form {
      width: 480px;
      margin: 0px auto;
      .el-form-item {
        text-align: left;
        .vscode {
          width: 150px;
        }
        .phoneCode {
          width: 212px;
        }
        .is-plain {
          margin: 0 10px;
        }
      }
    }
    .imgVscode {
      margin: 0 10px;
      display: inline-block;
      height: 36px;
      vertical-align: top;
      canvas {
        height: 36px;
      }
    }
  }
  @media only screen and (max-width: 1920px) {
    .mainBox {
      margin-top: 5%;
      //   height: 522px;
    }
  }
  @media screen and (min-width: 1440px) and (max-width: 1600px) {
    .mainBox {
      margin-top: 1%;
    }
  }
  @media screen and (min-width: 1280px) and (max-width: 1366px) {
    .mainBox {
      margin-top: 0;
      //   height: 450px;
    }
  }
  @media only screen and (max-width: 1280px) {
    .mainBox {
      margin-top: 3%;
      //   height: 420px;
      padding-bottom: 30px;

      .fourStep img {
        width: 124px;
      }
    }
  }
  .el-step__head.is-success {
    color: #009588;
    border-color: #009588;
  }
}

.container {
  background: #f2f4f6;
  /deep/ .topTitleBox {
    background: url('../../../static/img/loginImg/headerBG.png') no-repeat;
    background-size: 100% 100%;
    margin-bottom: 30px;
  }
}
// .saveBtn{
//     width: 100%;
// }
.saveBtn1 {
  margin-left: 72px;
}
.fourStep {
  text-align: center;
}
.vscodeBtn {
  width: 126px;
  height: 36px;
  padding: 0px;
  color: #009588;
  border: 1px solid #009588;
  cursor: pointer;
}
</style>
